{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:react-aria-components';
import typesDocs from 'docs:@react-types/shared/src/events.d.ts';
import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} from '@react-spectrum/docs';
import styles from '@react-spectrum/docs/src/docs.css';
import packageData from 'react-aria-components/package.json';
import Anatomy from '@react-aria/datepicker/docs/daterangepicker-anatomy.svg';
import ChevronRight from '@spectrum-icons/workflow/ChevronRight';
import {Divider} from '@react-spectrum/divider';
import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard';
import {Keyboard} from '@react-spectrum/text';
import {StarterKits} from '@react-spectrum/docs/src/StarterKits';

---
category: Buttons
keywords: [button, toggle button, aria, form]
type: component
---

# ToggleButton

<PageDescription>{docs.exports.ToggleButton.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['ToggleButton']}
  sourceData={[
    {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/button/'}
  ]} />

## Example

```tsx example
import {ToggleButton} from 'react-aria-components';

<ToggleButton>Pin</ToggleButton>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
@import "@react-aria/example-theme";

.react-aria-ToggleButton {
  color: var(--text-color);
  background: var(--button-background);
  border: 1px solid var(--border-color);
  forced-color-adjust: none;
  border-radius: 4px;
  appearance: none;
  vertical-align: middle;
  font-size: 1rem;
  text-align: center;
  margin: 0;
  outline: none;
  padding: 6px 10px;
  display: inline-flex;
  align-items: center;
  justify-content: center;

  &[data-pressed] {
    box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
    background: var(--button-background-pressed);
    border-color: var(--border-color-pressed);
  }

  &[data-selected] {
    background: var(--highlight-background);
    border-color: var(--highlight-background);
    color: var(--highlight-foreground);

    &[data-pressed] {
      background: var(--highlight-background-pressed);
      border-color: var(--highlight-background-pressed);
    }
  }

  &[data-focus-visible] {
    outline: 2px solid var(--focus-ring-color);
    outline-offset: 2px;
  }
}
```

</details>

## Features

Toggle buttons are similar to action buttons, but support an additional selection state
that is toggled when a user presses the button. There is no built-in HTML element that
represents a toggle button, so React Aria implements it using ARIA attributes.

* **Styleable** – Hover, press, keyboard focus, and selection states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.
* **Accessible** – Uses a native `<button>` element with the `aria-pressed `attribute, and supports the <Keyboard>Space</Keyboard> and <Keyboard>Enter</Keyboard> keys to toggle the selection state.
* **Cross-browser** – Mouse, touch, keyboard, and focus interactions are normalized to ensure consistency across browsers and devices.

Read our [blog post](/blog/building-a-button-part-1.html) about the complexities of building buttons that work well across devices and interaction methods to learn more.

## Anatomy

Toggle buttons consist of a clickable area usually containing a textual label or an icon
that users can click to toggle a selection state. In addition, keyboard users may toggle
the state using the <Keyboard>Space</Keyboard> or <Keyboard>Enter</Keyboard> keys.

If a visual label is not provided (e.g. an icon only button), then an `aria-label` or
`aria-labelledby` prop must be passed to identify the button to assistive technology.

## Starter kits

To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured [Storybook](https://storybook.js.org/) that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="togglebutton" />

## Selection

A default selection state for a toggle button can be set using the `defaultSelected` prop, or controlled with the `isSelected` prop. The `onChange` event is fired when the user presses the button, toggling the boolean. See React's documentation on
[uncontrolled components](https://reactjs.org/docs/uncontrolled-components.html) for more info.

```tsx example
import {Star} from 'lucide-react';

function Example() {
  let [isSelected, setSelected] = React.useState(false);

  return (
    <ToggleButton
      isSelected={isSelected}
      onChange={setSelected}
      aria-label="Star">
      <Star size={18} />
    </ToggleButton>
  );
}
```

## Disabled

A `ToggleButton` can be disabled using the `isDisabled` prop.

```tsx example
<ToggleButton isDisabled>Pin</ToggleButton>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-ToggleButton {
  &[data-disabled] {
    border-color: var(--border-color-disabled);
    background: var(--button-background);
    color: var(--text-color-disabled);
  }
}
```

</details>

## Props

<PropTable component={docs.exports.ToggleButton} links={docs.links} />

## Styling

React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin `className` attribute which can be targeted using CSS selectors. These follow the `react-aria-ComponentName` naming convention.

```css
.react-aria-ToggleButton {
  /* ... */
}
```

A custom `className` can also be specified on any component. This overrides the default `className` provided by React Aria with your own.

```jsx
<ToggleButton className="my-button">
  {/* ... */}
</ToggleButton>
```

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:

```css
.react-aria-ToggleButton[data-selected] {
  /* ... */
}
```

The `className` and `style` props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like [Tailwind](https://tailwindcss.com/).

```jsx
<ToggleButton className={({isSelected}) => isSelected ? 'bg-blue-600' : 'bg-gray-600'} />
```

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could swap an icon depending on the selection state.

```jsx
<ToggleButton>
  {({isSelected}) => (
    <>
      {isSelected ? <PinnedIcon /> : <UnpinnedIcon />}
      Pin
    </>
  )}
</ToggleButton>
```

The states, selectors, and render props for `ToggleButton` are documented below.

<StateTable properties={docs.exports.ToggleButtonRenderProps.properties} />

## Advanced customization

### Contexts

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in [mergeProps](mergeProps.html)).

<ContextTable components={['ToggleButton']} docs={docs} />

This example shows a `ButtonGroup` component that renders a group of buttons. The entire group can be marked as disabled via the `isDisabled` prop, which is passed to all child buttons via the `ButtonContext` provider.

```tsx example
import {ToggleButtonContext} from 'react-aria-components';
import {Star, Flag} from 'lucide-react';

interface ButtonGroupProps {
  children?: React.ReactNode,
  isDisabled?: boolean
}

function ButtonGroup({children, isDisabled}: ButtonGroupProps) {
  return (
    <div style={{display: 'flex', gap: 8}}>
      {/*- begin highlight -*/}
      <ToggleButtonContext.Provider value={{isDisabled}}>
      {/*- end highlight -*/}
        {children}
      </ToggleButtonContext.Provider>
    </div>
  );
}

<ButtonGroup isDisabled>
  <ToggleButton isSelected aria-label="Favorite"><Star size={18} /></ToggleButton>
  <ToggleButton aria-label="Flag"><Flag size={18} /></ToggleButton>
</ButtonGroup>
```

### Hooks

If you need to customize things further, such as intercepting events or customizing DOM elements, you can drop down to the lower level Hook-based API. Consume from `ToggleButtonContext` in your component with <TypeLink links={docs.links} type={docs.exports.useContextProps} /> to make it compatible with other React Aria Components. See [useToggleButton](useToggleButton.html) for more details.

This example uses [Framer Motion](https://www.framer.com/motion/) to create an `AnimatedToggleButton` component that animates based on the `isSelected` state. It can be used standalone or as a part of any React Aria component.

```tsx
import type {ToggleButtonProps} from 'react-aria-components';
import {ToggleButtonContext, useContextProps} from 'react-aria-components';
import {useToggleState} from 'react-stately';
import {useToggleButton} from 'react-aria';
import {motion} from 'motion/react';

const AnimatedToggleButton = React.forwardRef((props: ToggleButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
  // Merge the local props and ref with the ones provided via context.
  ///- begin highlight -///
  [props, ref] = useContextProps(props, ref, ButtonContext);
  ///- end highlight -///

  let state = useToggleState(props);
  let {buttonProps} = useToggleButton(props, state, ref);
  return (
    <motion.button
      {...buttonProps}
      ref={ref}
      animate={{
        scale: state.isSelected ? 1.2 : 1
      }}>
      {props.children}
    </motion.button>
  );
});
```
